<template>
	<view class="container">
		<view class="imgbox">
			<image src="../../static/head_icon.png" mode="aspectFill"></image>
		</view>

		<uni-forms ref="form" :model="user" :rules="rules" class="form">
			<uni-forms-item label="用户名" name="username">
				<uni-easyinput v-model="user.username" placeholder="请输入用户名" />
			</uni-forms-item>
			<uni-forms-item label="密码" name="password">
				<uni-easyinput type="password" v-model="user.password" placeholder="请输入密码" />
			</uni-forms-item>
			<uni-forms-item label="" name="">
				<button type="primary" @click="login">登录</button>
			</uni-forms-item>
		</uni-forms>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				user: {
					username: '张三',
					password: '123'
				},
				rules: {
					username: {
						rules: [{
							required: true,
							errorMessage: '请输入用户名'
						}]
					},
					password: {
						rules: [{
							required: true,
							errorMessage: '请输入密码'
						}, {
							minLength: 3,
							maxLength: 5,
							errorMessage: '密码的长度要在{minLength}和{maxLength}之间'
						}, {
							pattern: '\\d',
							errorMessage: '密码至少包含一个数字'
						}]
					}
				}
			}
		},
		methods: {
			login(e) {
				this.$refs.form.validate()// 触发表单验证
					.then((e) => {
						uni.request({
							url: 'http://localhost:8090/freshmenapp/user/login',
							method: 'POST',
							data: {
								name: this.user.username,
								password: this.user.password
							},
							success: res => {
								if (res.data.success) {
									uni.showToast({
										title: this.user.username + '登录成功'
									});
									uni.setStorageSync('userInfo', res.data.data)
									uni.navigateBack()
								} else {
									uni.showToast({
										icon: 'error',
										title: '用户名或密码错误'
									});
								}
							},
							fail: () => {
								uni.showToast({
									icon: 'error',
									title: '网络异常'
								});
							},
							complete: () => {}
						});
					})
					.catch((e) => {
						uni.showToast({
							icon: 'error',
							title: '请填写用户名和密码'
						});
					});
			}
		}
	}
</script>

<style>
	.container {
		width: 100%;
		height: 100%;
	}

	.imgbox {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin: 10%;
	}

	.imgbox image {
		width: 200rpx;
		height: 200rpx;
	}

	.form {
		margin: 0 5%;
		padding-top: 5%;
	}
</style>